<!doctype html>



  


<html class="theme-next mist use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="前端,AngularJS,图片裁剪," />





  <link rel="alternate" href="/atom.xml" title="Superlee's blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="本文的内容是博主在封装一个angular的图片裁剪工具时的一些心得和体验，记录下来，方便之后回顾。所涉及到的angular的技术：指令封装、指令依赖、H5资源接口FileReader">
<meta property="og:type" content="article">
<meta property="og:title" content="Angular图片裁剪1--本地图片读取及显示">
<meta property="og:url" content="http://superleehome.oschina.io/2016/07/31/Angular图片裁剪1--本地图片读取及显示/index.html">
<meta property="og:site_name" content="Superlee's blog">
<meta property="og:description" content="本文的内容是博主在封装一个angular的图片裁剪工具时的一些心得和体验，记录下来，方便之后回顾。所涉及到的angular的技术：指令封装、指令依赖、H5资源接口FileReader">
<meta property="og:image" content="http://superleehome.oschina.io/upload/clipImg1.gif">
<meta property="og:updated_time" content="2016-11-11T03:23:49.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Angular图片裁剪1--本地图片读取及显示">
<meta name="twitter:description" content="本文的内容是博主在封装一个angular的图片裁剪工具时的一些心得和体验，记录下来，方便之后回顾。所涉及到的angular的技术：指令封装、指令依赖、H5资源接口FileReader">
<meta name="twitter:image" content="http://superleehome.oschina.io/upload/clipImg1.gif">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 6311798335376197000,
      author: '博主'
    }
  };
</script>




  <link rel="canonical" href="http://superleehome.oschina.io/2016/07/31/Angular图片裁剪1--本地图片读取及显示/"/>

  <title> Angular图片裁剪1--本地图片读取及显示 | Superlee's blog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">Superlee's blog</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">时光且行</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于我
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Angular图片裁剪1--本地图片读取及显示
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-07-31T20:57:53+08:00" content="2016-07-31">
              2016-07-31
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/前端/" itemprop="url" rel="index">
                    <span itemprop="name">前端</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2016/07/31/Angular图片裁剪1--本地图片读取及显示/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="2016/07/31/Angular图片裁剪1--本地图片读取及显示/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          
             <span id="/2016/07/31/Angular图片裁剪1--本地图片读取及显示/" class="leancloud_visitors" data-flag-title="Angular图片裁剪1--本地图片读取及显示">
               &nbsp; | &nbsp;
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">阅读次数 </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文的内容是博主在封装一个angular的图片裁剪工具时的一些心得和体验，记录下来，方便之后回顾。<br>所涉及到的angular的技术：指令封装、指令依赖、H5资源接口FileReader</p>
<a id="more"></a>
<h3 id="需求说明"><a href="#需求说明" class="headerlink" title="需求说明"></a>需求说明</h3><p>点击按钮或div(按钮样式可自定义),跳出选取文件框，选取图片资源文件后，在模态对话框上进行图片处理，保存时在页面显示处理后图片内容。<br>效果显示图如下：<br><img src="/upload/clipImg1.gif" alt="效果图"></p>
<blockquote>
<p>本文暂未设计图片处理部分，关于图片处理，请参考下一篇文章</p>
</blockquote>
<h3 id="代码实现"><a href="#代码实现" class="headerlink" title="代码实现"></a>代码实现</h3><blockquote>
<h4 id="index-html"><a href="#index-html" class="headerlink" title="index.html"></a>index.html</h4></blockquote>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;!DOCTYPE html&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">"en"</span> <span class="attr">ng-app</span>=<span class="string">"MyApp"</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"UTF-8"</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span> <span class="attr">src</span>=<span class="string">"angular.min.js"</span>&gt;</span><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span> <span class="attr">src</span>=<span class="string">"app.js"</span>&gt;</span><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span> <span class="attr">src</span>=<span class="string">"directives.js"</span>&gt;</span><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></div><div class="line"></div><div class="line">	<span class="tag">&lt;<span class="name">link</span> <span class="attr">rel</span>=<span class="string">"stylesheet"</span> <span class="attr">type</span>=<span class="string">"text/css"</span> <span class="attr">href</span>=<span class="string">"bootstrap.min.css"</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">style</span> <span class="attr">type</span>=<span class="string">"text/css"</span>&gt;</span><span class="undefined"></span></div><div class="line">		.preAreaShow&#123;</div><div class="line">			display: block;</div><div class="line">			background-color: rgba(0, 0, 0, 0.5);</div><div class="line">		&#125;</div><div class="line">		.preAreaHide&#123;</div><div class="line">			display: none;</div><div class="line">		&#125;</div><div class="line">	<span class="tag">&lt;/<span class="name">style</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">div</span> <span class="attr">ng-controller</span>=<span class="string">"ImgCtrl"</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">img-upload-btn</span> <span class="attr">post-img</span>=<span class="string">"myImage"</span> <span class="attr">result-img</span>=<span class="string">"resultImg"</span>&gt;</span></div><div class="line">		    添加图片</div><div class="line">		<span class="tag">&lt;/<span class="name">img-upload-btn</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">div</span> <span class="attr">style</span>=<span class="string">"margin-top:30px;"</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">img</span> <span class="attr">ng-src</span>=<span class="string">"&#123;&#123;resultImg&#125;&#125;"</span> <span class="attr">style</span>=<span class="string">"max-width: 210px;"</span>&gt;</span></div><div class="line">		<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></div></pre></td></tr></table></figure>
<p>img-upload-btn标签是最终封装好的标签，post-img是选择的图片，result-img是最终生成的图片(经过裁剪等操作)<br>div&gt;img 为预览区域，展示处理完后的图片。</p>
<blockquote>
<h4 id="app-js"><a href="#app-js" class="headerlink" title="app.js"></a>app.js</h4></blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> myApp = angular.module(<span class="string">'MyApp'</span>, []);</div><div class="line"></div><div class="line">myApp.controller(<span class="string">'ImgCtrl'</span>, [<span class="string">'$scope'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">$scope</span>)</span>&#123;</div><div class="line"></div><div class="line">&#125;]);</div></pre></td></tr></table></figure>
<blockquote>
<h4 id="directives-js"><a href="#directives-js" class="headerlink" title="directives.js"></a>directives.js</h4></blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> myApp=angular.module(<span class="string">'MyApp'</span>);</div><div class="line"></div><div class="line">myApp.directive(<span class="string">'imgUploadBtn'</span>,<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">    <span class="keyword">return</span>&#123;</div><div class="line">        <span class="attr">restrict</span>:<span class="string">'E'</span>,</div><div class="line">        <span class="attr">transclude</span>:<span class="literal">true</span>,</div><div class="line">        <span class="attr">scope</span>:&#123;</div><div class="line">            <span class="attr">postImg</span>:<span class="string">'='</span>,</div><div class="line">            <span class="attr">resultImg</span>:<span class="string">'='</span></div><div class="line">        &#125;,</div><div class="line">        <span class="attr">controller</span>:<span class="function"><span class="keyword">function</span>(<span class="params">$scope</span>)</span>&#123;</div><div class="line">        	$scope.preImgShow=<span class="literal">false</span>;</div><div class="line">        	<span class="keyword">this</span>.hidePreImgArea=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">        		$scope.preImgShow=<span class="literal">false</span>;</div><div class="line">        	&#125;;</div><div class="line">        	<span class="keyword">this</span>.showPreImgArea=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">        		$scope.preImgShow=<span class="literal">true</span>;</div><div class="line">        	&#125;;</div><div class="line">        	<span class="keyword">this</span>.saveImg=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">        		<span class="comment">//<span class="doctag">TODO:</span> 处理裁剪后的图片逻辑</span></div><div class="line">        		$scope.resultImg=$scope.postImg;</div><div class="line">        		$scope.preImgShow=<span class="literal">false</span>;</div><div class="line">        	&#125;;</div><div class="line">        	$scope.hidePreImgArea=<span class="keyword">this</span>.hidePreImgArea;</div><div class="line">        	$scope.saveImg=<span class="keyword">this</span>.saveImg;</div><div class="line">        &#125;,</div><div class="line">        <span class="attr">templateUrl</span>:<span class="string">'tplPreviewImg.html'</span></div><div class="line">    &#125;</div><div class="line">&#125;).directive(<span class="string">"fileread"</span>, [<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</div><div class="line">    <span class="keyword">return</span> &#123;</div><div class="line">        <span class="attr">restrict</span>:<span class="string">'A'</span>,</div><div class="line">        <span class="attr">require</span>:<span class="string">'^imgUploadBtn'</span>,</div><div class="line">        <span class="attr">scope</span>: &#123;</div><div class="line">            <span class="attr">fileread</span>: <span class="string">"="</span></div><div class="line">        &#125;,</div><div class="line">        <span class="attr">link</span>: <span class="function"><span class="keyword">function</span> (<span class="params">scope, element, attributes,imgUploadBtnCtrl</span>) </span>&#123;</div><div class="line">            element.bind(<span class="string">"change"</span>, <span class="function"><span class="keyword">function</span> (<span class="params">evt</span>) </span>&#123;</div><div class="line">                <span class="keyword">var</span> file=evt.currentTarget.files[<span class="number">0</span>];</div><div class="line">                <span class="keyword">var</span> reader = <span class="keyword">new</span> FileReader();</div><div class="line">                reader.onload = <span class="function"><span class="keyword">function</span> (<span class="params">evt</span>) </span>&#123;</div><div class="line">                    scope.$apply(<span class="function"><span class="keyword">function</span>(<span class="params">$scope</span>)</span>&#123;</div><div class="line">                        scope.fileread=evt.target.result;</div><div class="line">                    &#125;);</div><div class="line">                &#125;;</div><div class="line">                reader.readAsDataURL(file);</div><div class="line">                imgUploadBtnCtrl.showPreImgArea();</div><div class="line">            &#125;);</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;]).directive(<span class="string">'imgBtn'</span>,<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">	<span class="keyword">return</span>&#123;</div><div class="line">		<span class="attr">restrict</span>:<span class="string">'A'</span>,</div><div class="line">		<span class="attr">link</span>:<span class="function"><span class="keyword">function</span>(<span class="params">scope,element,attr</span>)</span>&#123;</div><div class="line">			element.bind(<span class="string">'click'</span>,<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">            	<span class="comment">//查找input文件选择框</span></div><div class="line">                <span class="built_in">document</span>.getElementById(<span class="string">'imgFile'</span>).click();</div><div class="line">            &#125;);</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p>这里我们封装了3个指令，相关作用及介绍如下：</p>
<ul>
<li>imgUploadBtn:我们最终在html页面上调用的指令（html页面上标签使用中划线方式使用，指令里需要使用驼峰标识）<ul>
<li>restrict:指令标识，E标识该指令为一个dom元素element,其他的还有A(attribute,属性),C(class，类),M(注释),后两者不常用。这些标识也可以结合使用，如’AE’,’AECM’等;</li>
<li>transclude:定义是否将当前元素的内容转移到模板中,并使用ng-transclude指令,用来告诉指令把内容转移到的位置比如我们在页面的自定义标签里写了“添加图片”，然后在button按钮上使用ng-transclude，那么button就会写上”添加图片”;</li>
<li>scope:定义该指令作用域，我们使用的是{}，表示新建一个作用域，里面引用了父作用域的两个变量（ps:关于angular作用域相关内容，请期待下一篇博客）</li>
<li>controller:该指令的控制器，里面为当前作用域定义了一个变量preImgShow，和两个函数hidePreImgArea、saveImg，并使用this暴露三个公共接口，以方便继承它的指令使用;</li>
<li>templateUrl:模版url地址</li>
</ul>
</li>
<li>fileread:读取本地图片相关方法，依赖上面的imgUploadBtn，指令里的内容介绍如下(与上面重复的不再赘述)<ul>
<li>require:指令依赖，^imgUploadBtn 表示从父节点上寻找imgUploadBtn指令，并添加到该当前fileread指令依赖中，即注入到link函数第四个参数ctrl中。另外还可以使用前缀?,此前缀将告诉$compile服务，如果所需的controller没找到，不要抛出异常.<br>关于指令通信的相关知识点，请期待下一篇文章</li>
<li>link:以编程的方式操作DOM，包括添加监听器、进行双向数据绑定等操作,负责在模型和数据之间进行数据关联，与compile区别是compile是以编程的方式修改DOM模板的副本。关于link和compile详细内容，请期待下一篇博客</li>
</ul>
</li>
<li>imgBtn：监听按钮点击事件，当按钮点击时，我们调用input文件选择框的click方法，即可选择文件。相当于我们将选择文件的input的点击事件委托给了按钮，这样我们就能自己设计好看的样式而不必使用原生input(type=’file’)的样式。</li>
</ul>
<blockquote>
<h4 id="tplPreviewImg-html"><a href="#tplPreviewImg-html" class="headerlink" title="tplPreviewImg.html"></a>tplPreviewImg.html</h4></blockquote>
<p>按钮、input选择框、模态预览框相关html内容<br><figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">btn</span> <span class="attr">class</span>=<span class="string">"btn btn-info"</span> <span class="attr">id</span>=<span class="string">"uploadBtn"</span> <span class="attr">ng-transclude</span> <span class="attr">img-btn</span>&gt;</span><span class="tag">&lt;/<span class="name">btn</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"file"</span> <span class="attr">fileread</span>=<span class="string">"postImg"</span> <span class="attr">pre-img-show</span>=<span class="string">"&#123;&#123;preImgShow&#125;&#125;"</span>  <span class="attr">id</span>=<span class="string">"imgFile"</span> <span class="attr">accept</span>=<span class="string">"image/gif,image/jpeg,image/png"</span> <span class="attr">style</span>=<span class="string">"display:none"</span>/&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"modal"</span> <span class="attr">ng-class</span>=<span class="string">"&#123;true:'preAreaShow',false:'preAreaHide'&#125;[preImgShow||false]"</span> <span class="attr">onselectstart</span>=<span class="string">"return false"</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"modal-dialog"</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"modal-content"</span>&gt;</span></div><div class="line">            <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"modal-header"</span>&gt;</span></div><div class="line">                <span class="tag">&lt;<span class="name">h4</span> <span class="attr">class</span>=<span class="string">"modal-title"</span>&gt;</span>图片预览<span class="tag">&lt;/<span class="name">h4</span>&gt;</span></div><div class="line">            <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">            <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"modal-body"</span>&gt;</span></div><div class="line">                <span class="tag">&lt;<span class="name">img</span> <span class="attr">ng-src</span>=<span class="string">"&#123;&#123;postImg&#125;&#125;"</span> <span class="attr">result-img</span>=<span class="string">"&#123;&#123;resultImg&#125;&#125;"</span> <span class="attr">style</span>=<span class="string">"max-width:500px;max-height:300px;margin:0 auto;display:block;"</span> /&gt;</span></div><div class="line">            <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">            <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"modal-footer"</span>&gt;</span></div><div class="line">                <span class="tag">&lt;<span class="name">button</span> <span class="attr">type</span>=<span class="string">"button"</span> <span class="attr">class</span>=<span class="string">"btn btn-default"</span> <span class="attr">ng-click</span>=<span class="string">"hidePreImgArea()"</span>&gt;</span>放弃<span class="tag">&lt;/<span class="name">button</span>&gt;</span></div><div class="line">                <span class="tag">&lt;<span class="name">button</span> <span class="attr">type</span>=<span class="string">"button"</span> <span class="attr">class</span>=<span class="string">"btn btn-primary"</span> <span class="attr">ng-click</span>=<span class="string">"saveImg()"</span>&gt;</span>保存<span class="tag">&lt;/<span class="name">button</span>&gt;</span></div><div class="line">            <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">        <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">	<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></div></pre></td></tr></table></figure></p>
<p>以上就是关于angular图片选择及预览的相关内容，下一节我们将继续讨论如何进行图片的裁剪及保存</p>

      
      <hr>
      <p>
         博客: <a href="http://superleehome.oschina.io">http://superleehome.oschina.io/</a>
         <br>
         作者: <a href="http://superleehome.oschina.io/about">Superlee</a>
      </p>
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>坚持干货知识技术分享，您的支持将鼓励我继续创作！</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
      
        <div id="alipay" style="display: inline-block">
          <img id="alipay_qr" src="/images/alipay.jpg" alt="Superlee Alipay"/>
          <p>支付宝打赏</p>
        </div>
      
    </div>
  </div>


      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/前端/" rel="tag">#前端</a>
          
            <a href="/tags/AngularJS/" rel="tag">#AngularJS</a>
          
            <a href="/tags/图片裁剪/" rel="tag">#图片裁剪</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/07/30/CSS浮动知识整理/" rel="next" title="CSS浮动知识整理">
                <i class="fa fa-chevron-left"></i> CSS浮动知识整理
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/08/08/LeetCode-Reverse-String/" rel="prev" title="[LeetCode]Reverse String">
                [LeetCode]Reverse String <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        <div class="ds-share flat" data-thread-key="2016/07/31/Angular图片裁剪1--本地图片读取及显示/"
     data-title="Angular图片裁剪1--本地图片读取及显示"
     data-content=""
     data-url="http://superleehome.oschina.io/2016/07/31/Angular图片裁剪1--本地图片读取及显示/">
  <div class="ds-share-inline">
    <ul  class="ds-share-icons-16">

      <li data-toggle="ds-share-icons-more"><a class="ds-more" href="javascript:void(0);">分享到：</a></li>
      <li><a class="ds-weibo" href="javascript:void(0);" data-service="weibo">微博</a></li>
      <li><a class="ds-qzone" href="javascript:void(0);" data-service="qzone">QQ空间</a></li>
      <li><a class="ds-qqt" href="javascript:void(0);" data-service="qqt">腾讯微博</a></li>
      <li><a class="ds-wechat" href="javascript:void(0);" data-service="wechat">微信</a></li>

    </ul>
    <div class="ds-share-icons-more">
    </div>
  </div>
</div>
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="2016/07/31/Angular图片裁剪1--本地图片读取及显示/"
           data-title="Angular图片裁剪1--本地图片读取及显示" data-url="http://superleehome.oschina.io/2016/07/31/Angular图片裁剪1--本地图片读取及显示/">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.jpg"
               alt="Superlee" />
          <p class="site-author-name" itemprop="name">Superlee</p>
          <p class="site-description motion-element" itemprop="description">青春都一饷，且把浮生，换了代码轻狂~</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">15</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">6</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">14</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/Superlee2013" target="_blank" title="Github">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  Github
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://geek.csdn.net/" title="极客头条" target="_blank">极客头条</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://toutiao.io/" title="开发者头条" target="_blank">开发者头条</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.iteye.com/" title="ITEye" target="_blank">ITEye</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://leetcode.com/" title="LeetCode" target="_blank">LeetCode</a>
                </li>
              
            </ul>
          </div>
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#需求说明"><span class="nav-number">1.</span> <span class="nav-text">需求说明</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#代码实现"><span class="nav-number">2.</span> <span class="nav-text">代码实现</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#index-html"><span class="nav-number">2.1.</span> <span class="nav-text">index.html</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#app-js"><span class="nav-number">2.2.</span> <span class="nav-text">app.js</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#directives-js"><span class="nav-number">2.3.</span> <span class="nav-text">directives.js</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#tplPreviewImg-html"><span class="nav-number">2.4.</span> <span class="nav-text">tplPreviewImg.html</span></a></li></ol></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        

<div class="busuanzi-count">

  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">您是第<span class="busuanzi-value" id="busuanzi_value_site_uv"></span>位小伙伴</span>
  

  
    <span class="site-pv">我被看了<span class="busuanzi-value" id="busuanzi_value_site_pv"></span>次</span>
  
  
</div>



        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2016</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Superlee</span>
  <span class="with-love">
        <i class="fa fa-envelope-o"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">superlee4life@foxmail.com</span>
</div>

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"superleeblog2"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
    <script src="/vendors/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>
    <script src="/js/src/hook-duoshuo.js"></script>
  






  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
       search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();

    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
    'use strict';
    $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
            // get the contents from search data
            isfetched = true;
            $('.popup').detach().appendTo('.header-inner');
            var datas = $( "entry", xmlResponse ).map(function() {
                return {
                    title: $( "title", this ).text(),
                    content: $("content",this).text(),
                    url: $( "url" , this).text()
                };
            }).get();
            var $input = document.getElementById(search_id);
            var $resultContent = document.getElementById(content_id);
            $input.addEventListener('input', function(){
                var matchcounts = 0;
                var str='<ul class=\"search-result-list\">';
                var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                $resultContent.innerHTML = "";
                if (this.value.trim().length > 1) {
                // perform local searching
                datas.forEach(function(data) {
                    var isMatch = true;
                    var content_index = [];
                    var data_title = data.title.trim().toLowerCase();
                    var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                    var data_url = data.url;
                    var index_title = -1;
                    var index_content = -1;
                    var first_occur = -1;
                    // only match artiles with not empty titles and contents
                    if(data_title != '' && data_content != '') {
                        keywords.forEach(function(keyword, i) {
                            index_title = data_title.indexOf(keyword);
                            index_content = data_content.indexOf(keyword);
                            if( index_title < 0 && index_content < 0 ){
                                isMatch = false;
                            } else {
                                if (index_content < 0) {
                                    index_content = 0;
                                }
                                if (i == 0) {
                                    first_occur = index_content;
                                }
                            }
                        });
                    }
                    // show search results
                    if (isMatch) {
                        matchcounts += 1;
                        str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                        var content = data.content.trim().replace(/<[^>]+>/g,"");
                        if (first_occur >= 0) {
                            // cut out 100 characters
                            var start = first_occur - 20;
                            var end = first_occur + 80;
                            if(start < 0){
                                start = 0;
                            }
                            if(start == 0){
                                end = 50;
                            }
                            if(end > content.length){
                                end = content.length;
                            }
                            var match_content = content.substring(start, end);
                            // highlight all keywords
                            keywords.forEach(function(keyword){
                                var regS = new RegExp(keyword, "gi");
                                match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                            });

                            str += "<p class=\"search-result\">" + match_content +"...</p>"
                        }
                        str += "</li>";
                    }
                })};
                str += "</ul>";
                if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
                if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
                $resultContent.innerHTML = str;
            });
            proceedsearch();
        }
    });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };

    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  

  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("x9h2WvWJwEXLMxFiGxoO6OvY-gzGzoHsz", "oc8OE6Iruzw7yKaiU0dU6QDr");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

</body>
</html>
